#pragma once

#include <functional>
#include <pthread.h>
#include "Socket.hpp"

using namespace Socket_ns;


using service_t = std::function<std::string(std::string&)>;// 包装的 Service 中的处理 IO 的函数

class TcpServer
{
public:
    TcpServer(service_t service, uint16_t port)
        : _port(port), _isrunning(false), _sockfd(std::make_shared<TcpSocket>()), _service(service)
    {
        _sockfd->BuildListenSocket(_port);
    }
    // 内部类
    class ThreadData
    {
    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        Inet_Addr _addr;

    public:
        ThreadData(SockSPtr sockfd, TcpServer *self, const Inet_Addr &addr)
            : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            Inet_Addr client;
            SockSPtr sock = _sockfd->Accepter(&client);
            if (sock == nullptr)
                continue;
            LOG(INFO, "get a new link, client info: %s, sockfd is: %d\n", client.AddrStr().c_str(), sock->Sockfd());
            // 采用多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(sock, this, client);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _isrunning = false;
    }

    static void *Execute(void *args) // 这里是在类的内部，有默认的 this 所以得用static 修饰
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        std::string requeststr;
        ssize_t n = td->_sockfd->Recv(&requeststr);// 目前默认是一个完整的报文 --- bug
        if(n > 0)
        {
            std::string reaponsestr = td->_self->_service(requeststr);
            td->_sockfd->Send(reaponsestr);
        }
        td->_sockfd->Close();// 回调回来，将 sockfd 关闭
        delete td;
        return nullptr;
    }

private:
    uint16_t _port;     // 端口
    bool _isrunning;    // 运行状态
    SockSPtr _sockfd;   // 父类对象
    service_t _service; // IO 回调的函数
};